package com.example.AIstudy.controller;

import com.example.AIstudy.domain.CompositionDetail;
import com.example.AIstudy.domain.Exercise;
import com.example.AIstudy.exception.AIstudyException;
import com.example.AIstudy.service.ExerciseService;
import com.example.AIstudy.util.FileUtil;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/photo")
@Api(tags = "照片上传API")
public class UploadController {

    @Autowired
    ExerciseService exerciseService;

    @PostMapping("/upload")
    @ApiOperation("上传照片")
    public String uploadPhoto(MultipartFile file) throws AIstudyException {
        try{
            String oldName=file.getOriginalFilename();
            String oleFileType=oldName.substring(oldName.lastIndexOf('.'));
            String newFileName=System.currentTimeMillis()+oleFileType;
            System.out.println(newFileName);
            FileUtil.uploadFile(file.getBytes(), FileUtil.getUploadFilePath(), newFileName);
            return "/photo/"+newFileName;
        }
        catch (Exception e){
            throw new AIstudyException(AIstudyException.ErrorType.IO_EXCEPTION,"照片上传失败");
        }
    }
    @PostMapping("/uploadForQuestion")
    @ApiOperation("上传图片自动识别获取题目信息,以字符串的方式返回，这个接口需要指定题目的类型")
    public Object uploadPhotoForOCR(@ApiParam("拍照文件")@RequestParam(value = "file")MultipartFile file,
                                    @ApiParam("题目类型")@RequestParam(value = "type")String type) throws AIstudyException {
        try{
//            //把上传的文件直接转换成base64的形式\
//            String base64EncoderImg = Base64.encodeBase64String(file.getBytes());
//            base64EncoderImg = "data:image/png;base64," + base64EncoderImg;
            String oldName=file.getOriginalFilename();
            String oleFileType=oldName.substring(oldName.lastIndexOf('.'));
            String newFileName=System.currentTimeMillis()+oleFileType;
            System.out.println(newFileName);
            FileUtil.uploadFile(file.getBytes(), FileUtil.getUploadFilePath(), newFileName);
            String photoURL=newFileName;
            try{
                //李妃 python环境
                String anacondaUrl="python";
                //获取python的执行文件地址
                String apiurL=new File(".").getCanonicalPath()+"/python-api/ocr_api.py";
                //传递的参数
                String[] arg = new String[]{anacondaUrl, apiurL, photoURL ,type};
                //选择和阅读需要更换位置
                if(type.equals("xuanze")||type.equals("yuedu")||type.equals("zuowentimu")||type.equals("fanyitimu")){
                    apiurL=new File(".").getCanonicalPath()+"/python-api/main/ocr_v2.py";
                    arg = new String[]{anacondaUrl, apiurL, photoURL};
                }
                Process proc = Runtime.getRuntime().exec(arg);
                int res = proc.waitFor();
                System.out.println(res);
                if (res == 0) {
                    System.out.println("成功执行");
                    //成功执行 获取输出信息
                    String line=null;
                    BufferedReader inData = new BufferedReader(new InputStreamReader(proc.getInputStream(), "gb2312"));
                    StringBuilder builder=new StringBuilder();
                    while ((line = inData.readLine()) != null){
                        if(line.equals("end_for_list"))break;
                        builder.append(line);
                        System.out.println(line);
                    }
                    inData.close();
                    if(type.equals("xuanze")||type.equals("yuedu")||type.equals("zuowentimu")||type.equals("fanyitimu")){
                        Gson gson = new Gson();
                        Exercise exercise = gson.fromJson(builder.toString(), Exercise.class);
                        return exercise;
                    }
                    return builder.toString();
                }else{
                    System.out.println("执行错误");
                    //未成功执行 获取错误输出信息
                    String line=null;
                    BufferedReader inError = new BufferedReader(new InputStreamReader(proc.getErrorStream(), "gb2312"));
                    while ((line = inError.readLine()) != null) {
                        System.out.println(line);
                        throw new AIstudyException(AIstudyException.ErrorType.IO_EXCEPTION,"自动识别题目信息失败");
                    }
                    inError.close();
                }
                proc.waitFor();
            }catch (IOException | InterruptedException e){
                throw new AIstudyException(AIstudyException.ErrorType.IO_EXCEPTION,"自动识别题目信息失败");
            }
            return null;
        }
        catch (Exception e){
            throw new AIstudyException(AIstudyException.ErrorType.IO_EXCEPTION,"照片上传失败");
        }
    }
    @PostMapping("/uploadForSearch")
    @ApiOperation("上传图片自动匹配原有的题库,返回匹配的题目和识别出来的题目")
    public List<Object> uploadPhotoForSearch(@ApiParam("拍照文件")@RequestParam(value = "file")MultipartFile file) throws AIstudyException {
        try{
            String oldName=file.getOriginalFilename();
            String oleFileType=oldName.substring(oldName.lastIndexOf('.'));
            String newFileName=System.currentTimeMillis()+oleFileType;
            System.out.println(newFileName);
            FileUtil.uploadFile(file.getBytes(), FileUtil.getUploadFilePath(), newFileName);
            String photoURL=newFileName;
            try{
                //李妃 python环境
                String anacondaUrl="python";
                //获取python的执行文件地址
                String apiurL=new File(".").getCanonicalPath()+"/python-api/main/ocr_v2.py";
//                String apiurL=new File(".").getCanonicalPath()+"/python-api/try.py";
                //传递的参数
                String[] arg = new String[]{anacondaUrl, apiurL, photoURL};
                Process proc = Runtime.getRuntime().exec(arg);
                int res = proc.waitFor();
                System.out.println(res);
                List<Object> return_data = Arrays.asList(new Object[4]);
                if (res == 0) {
                    System.out.println("成功执行");
                    //成功执行 获取输出信息
                    String line=null;
                    BufferedReader inData = new BufferedReader(new InputStreamReader(proc.getInputStream(), "gb2312"));
                    StringBuilder builder=new StringBuilder();
                    Boolean flag=true;
                    //匹配题目对应的ID列表
                    List<String>esidList=new ArrayList<>(4);
                    while ((line = inData.readLine()) != null){
                        if(flag){
                            if(line.equals("end_for_list")){
                                Gson gson = new Gson();
                                Exercise exercise = gson.fromJson(builder.toString(), Exercise.class);
//                                flag=false;
                                return_data.set(3, exercise);
//                                return_data.set(3, builder.toString());
                                flag=false;
//                                System.out.println(builder.toString());
                            }
                            //构建一个字符串
                            builder.append(line);
                            builder.append("\n");
                            System.out.println(line);
                        }
                        //封装匹配的题目对应的ID
                        else{
                            System.out.println(line);
                            esidList.add(line);
                        }
                    }
                    //根据匹配到的ID查询对应的匹配题目并返回
                    List<Exercise>exercises=exerciseService.getExerviceByesList(esidList);
                            for(int i=0;i<3;i++){
                                return_data.set(i,exercises.get(i));
                            }
                    inData.close();
                    return return_data;
                }else{
                    System.out.println("执行错误");
                    //未成功执行 获取错误输出信息
                    String line=null;
                    BufferedReader inError = new BufferedReader(new InputStreamReader(proc.getErrorStream(), "gb2312"));
                    while ((line = inError.readLine()) != null) {
                        System.out.println(line);
                        throw new AIstudyException(AIstudyException.ErrorType.IO_EXCEPTION,"自动识别题目信息失败");
                    }
                    inError.close();
                }
                proc.waitFor();
            }catch (IOException | InterruptedException e){
                System.out.println(e.getMessage());
                throw new AIstudyException(AIstudyException.ErrorType.IO_EXCEPTION,"自动识别题目信息失败");
            }
            return null;
        }
        catch (Exception e){
            System.out.println(e.getMessage());
            throw new AIstudyException(AIstudyException.ErrorType.IO_EXCEPTION,"照片上传失败");
        }
    }
}
